<template>
  <div>
    <div v-if="qid == null">
      <a-page-header
        :ghost="false"
        title="题库管理/THE QUESTION BANK MANAGEMENT"
      />
      <a-card
        :bordered="false"
        style="margin-left: 16px;margin-right: 16px;margin-top: 16px;"
      >
        <a-card :bordered="false">
          <a-row :gutter="16">
            <a-col :span="20">
              <a-form-model layout="inline">
                <a-form-model-item label="题库名称">
                  <a-input
                    placeholder="请输入题库名称"
                    v-model="questionBankName"
                  />
                </a-form-model-item>

                <a-form-model-item>
                  <a-button type="primary" @click="findQuestionBank">
                    搜索
                  </a-button>
                </a-form-model-item>
                <a-form-model-item>
                  <a-button @click="resetSearch">
                    重置
                  </a-button>
                </a-form-model-item>
              </a-form-model>
            </a-col>
            <a-col :span="4">
              <a-form-model layout="inline">
                <a-form-model-item>
                  <a-button
                    type="primary"
                    @click="showModal"
                    style="width: 100px;"
                  >
                    创建题库
                  </a-button>
                </a-form-model-item>
              </a-form-model>
            </a-col>
          </a-row>
        </a-card>
        <a-spin :spinning="spinning">
          <a-table
            style="margin-top: 16px;"
            :columns="columns"
            :data-source="data"
          >
            <span slot="name" slot-scope="text">{{ text }}</span>
            <span slot="questionTitle">题库名称</span>
            <span slot="tags" slot-scope="tags">
              <a-tag
                v-for="tag in tags"
                :key="tag"
                :color="
                  tag.length <= 3
                    ? 'volcano'
                    : tag.length > 4
                    ? 'geekblue'
                    : 'green'
                "
              >
                {{ tag.toUpperCase() }}
              </a-tag>
            </span>
            <!-- <span slot="action" slot-scope="text,index"> -->
            <template slot="action" slot-scope="text, record">
              <span slot="action">
                <a @click="getDescribe(record)">试题</a>
                <a-divider type="vertical" />
                <a @click="showModifyQuestionModel(record)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确认删除此题库?"
                  ok-text="确定删除"
                  cancel-text="取消"
                  @confirm="delQuestion(record)"
                >
                  <a style="color: #FF4D4F;">删除</a>
                </a-popconfirm>
              </span>
            </template>
          </a-table>
        </a-spin>
      </a-card>

      <!-- 创建题库 -->
      <a-modal
        v-model="createModelVisible"
        title="题库设置"
        @ok="postCreateQuestionBank"
        okText="确定"
        cancelText="取消"
        :maskClosable="false"
      >
        <a-form-model layout="inline">
          <a-form-model-item label="题库名称">
            <a-input
              placeholder="请输入题库名称"
              v-model="createQuestionBankFrom.name"
            />
          </a-form-model-item>
        </a-form-model>
        <a-form-model layout="inline">
          <a-form-model-item label="题库标签">
            <template v-for="(tag, index) in tags">
              <a-tooltip v-if="tag.length > 10" :key="tag" :title="tag">
                <a-tag
                  :key="tag"
                  :closable="index >= 0"
                  @close="() => handleClose(tag)"
                >
                  {{ `${tag.slice(0, 10)}...` }}
                </a-tag>
              </a-tooltip>
              <a-tag
                v-else
                :key="tag"
                :closable="index >= 0"
                @close="() => handleClose(tag)"
              >
                {{ tag }}
              </a-tag>
            </template>
            <a-input
              v-if="inputVisible"
              ref="input"
              type="text"
              size="small"
              :style="{ width: '78px' }"
              :value="inputValue"
              @change="handleInputChange"
              @blur="handleInputConfirm"
              @keyup.enter="handleInputConfirm"
            />
            <a-tag
              v-else
              style="background: #fff; borderStyle: dashed;"
              @click="showInput"
            >
              <a-icon type="plus" /> 新建标签
            </a-tag>
          </a-form-model-item>
        </a-form-model>
      </a-modal>

      <!-- 修改题库 -->
      <a-modal
        v-model="modifyModelVisible"
        title="修改题库基础信息"
        @ok="postModifyQuestionBank"
        @cancel="resetForm"
        okText="确定"
        cancelText="取消"
        :maskClosable="false"
      >
        <a-form-model layout="inline">
          <a-form-model-item label="题库名称">
            <a-input
              placeholder="请输入题库名称"
              v-model="createQuestionBankFrom.name"
            />
          </a-form-model-item>
        </a-form-model>
        <a-form-model layout="inline">
          <a-form-model-item label="题库标签">
            <template v-for="(tag, index) in tags">
              <a-tooltip v-if="tag.length > 10" :key="tag" :title="tag">
                <a-tag
                  :key="tag"
                  :closable="index >= 0"
                  @close="() => handleClose(tag)"
                >
                  {{ `${tag.slice(0, 10)}...` }}
                </a-tag>
              </a-tooltip>
              <a-tag
                v-else
                :key="tag"
                :closable="index >= 0"
                @close="() => handleClose(tag)"
              >
                {{ tag }}
              </a-tag>
            </template>
            <a-input
              v-if="inputVisible"
              ref="input"
              type="text"
              size="small"
              :style="{ width: '78px' }"
              :value="inputValue"
              @change="handleInputChange"
              @blur="handleInputConfirm"
              @keyup.enter="handleInputConfirm"
            />
            <a-tag
              v-else
              style="background: #fff; borderStyle: dashed;"
              @click="showInput"
            >
              <a-icon type="plus" /> 新建标签
            </a-tag>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </div>
    <div v-else>
      <QuestionBank :qid="qid"> </QuestionBank>
    </div>
  </div>
</template>
<script>
import QuestionBank from "../Questions/QuestionBank";

const columns = [
  {
    dataIndex: "name",
    key: "name",
    slots: { title: "questionTitle" },
    scopedSlots: { customRender: "name" },
    width: 180
  },
  {
    title: "题量",
    dataIndex: "countTotal",
    key: "countTotal",
    width: 80
  },
  // {
  //   title: "单选",
  //   dataIndex: "countRadio",
  //   key: "countRadio",
  //   width: 80
  // },
  // {
  //   title: "多选",
  //   dataIndex: "countMultiSelect",
  //   key: "countMultiSelect",
  //   width: 80
  // },
  // {
  //   title: "判断",
  //   dataIndex: "countTrueOrFalse",
  //   key: "countTrueOrFalse",
  //   width: 80
  // },
  // {
  //   title: "填空",
  //   dataIndex: "countGap",
  //   key: "countGap",
  //   width: 80
  // },
  // {
  //   title: "问答",
  //   dataIndex: "countEssay",
  //   key: "countEssay",
  //   width: 80
  // },
  {
    title: "标签",
    key: "tags",
    dataIndex: "tags",
    scopedSlots: { customRender: "tags" },
    ellipsis: true
  },
  {
    title: "创建时间",
    dataIndex: "createdTime",
    key: "createdTime",
    width: 180
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" }
  }
];

export default {
  data() {
    return {
      questionBankName: "", // 用于模糊查询
      spinning: false,
      data: [],
      columns,
      createModelVisible: false,
      modifyModelVisible: false,
      qid: this.$route.query.qid,
      createQuestionBankFrom: {
        name: "",
        tags: ""
      },
      tags: [],
      inputVisible: false,
      inputValue: "",
      questionId: 0
    };
  },
  components: { QuestionBank },
  methods: {
    showModal() {
      this.createModelVisible = true;
    },
    showModifyQuestionModel(record) {
      // 显示模块
      this.modifyModelVisible = true;
      // 给表赋值
      this.createQuestionBankFrom.name = record.name;
      this.tags = record.tags;
      // 设置需要提交的id
      this.questionId = record.id;
      console.log(record);
    },
    postModifyQuestionBank() {
      let str = "";
      let len = this.tags.length;
      // 拼接字符串
      for (let i = 0; i < len; i++) {
        if (i < len - 1) {
          str = str + this.tags[i] + ",";
        } else {
          str = str + this.tags[i] + "";
        }
      }
      this.createQuestionBankFrom.tags = str.toString();
      console.log(this.createQuestionBankFrom);
      this.$axios
        .post(
          "/modify/questionBank/info/" + this.questionId,
          this.createQuestionBankFrom,
          {
            headers: {
              Authorization: localStorage.getItem("token")
            }
          }
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 200) {
            this.getBasicInfo();
            this.$message.success(res.data.msg);
            this.modifyModelVisible = false;
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    resetForm() {
      this.createQuestionBankFrom.name = "";
      this.questionId = 0;
      this.tags = [];
    },
    // 创建题库
    postCreateQuestionBank(e) {
      // 定义一个str存放tags
      let str = "";
      let len = this.tags.length;
      // 拼接字符串
      for (let i = 0; i < len; i++) {
        if (i < len - 1) {
          str = str + this.tags[i] + ",";
        } else {
          str = str + this.tags[i] + "";
        }
      }
      console.log(str);
      this.createQuestionBankFrom.tags = str.toString();
      console.log(this.createQuestionBankFrom.tags);
      // console.log(JSON.stringify(this.createQuestionBankFrom.tags));
      this.$axios
        .post("/create/questionBank/info", this.createQuestionBankFrom, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          console.log(res);
          if (res.data.code == 200) {
            this.getBasicInfo();
            this.$message.success(res.data.msg);
            this.createModelVisible = false;
            this.resetForm();
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    getDescribe(record) {
      // 直接调用$router.push 实现携带参数的跳转
      // this.$router.push({
      //   path: `/home/exam/questionManagement?qid=${id}`
      // });
      this.qid = record.id;
    },
    handleClose(removedTag) {
      const tags = this.tags.filter(tag => tag !== removedTag);
      console.log(tags);
      this.tags = tags;
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(function() {
        this.$refs.input.focus();
      });
    },
    handleInputChange(e) {
      this.inputValue = e.target.value;
    },
    handleInputConfirm() {
      const inputValue = this.inputValue;
      let tags = this.tags;
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue];
      }
      console.log(tags);
      Object.assign(this, {
        tags,
        inputVisible: false,
        inputValue: ""
      });
    },
    // 获取题库基础信息
    getBasicInfo() {
      this.spinning = true;
      this.$axios
        .get("/get/questionBank/info", {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          console.log(res);
          // this.data[0].tags = res.data.data[0].tags.split(",");
          // console.log(this.data[0].tags);
          this.data = res.data.data;
          for (let i = 0; i < res.data.data.length; i++) {
            this.data[i].key = this.data[i].id;
            this.data[i].tags = this.data[i].tags.split(",");
            this.data[i].createdTime = this.data[i].createdTime.replace(
              "T",
              " "
            );
          }
        });
      this.spinning = false;
    },
    // 删除题库信息
    delQuestion(record) {
      // 该题库所对应的id
      console.log(record.id);
      this.$axios
        .delete("/delete/questionBank/info/" + record.id, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.getBasicInfo();
            this.$message.success(res.data.msg);
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    findQuestionBank() {
      if (this.questionBankName.match(/^[ ]*$/)) {
        return this.$message.error("不能为空");
      }
      this.spinning = true;
      if (this.questionBankName.replace(/(^s*)|(s*$)/g, "").length == 0) {
        this.getBasicInfo();
        return;
      }
      this.$axios
        .get("/find/questionBank/" + this.questionBankName, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.data = res.data.data;
            for (let i = 0; i < res.data.data.length; i++) {
              this.data[i].key = this.data[i].id;
              this.data[i].tags = this.data[i].tags.split(",");
              this.data[i].createdTime = this.data[i].createdTime.replace(
                "T",
                " "
              );
            }
          } else {
            this.$message.error(res.data.msg);
          }
        });
      this.spinning = false;
    }, // 重置搜索
    resetSearch() {
      this.questionBankName = "";
      this.getBasicInfo();
    }
  },
  created() {
    // console.log("route");
    // console.log(this.$route);
    this.getBasicInfo();
  },
  destroyed() {
    if (this.$route.name == "questionManagement") {
      console.log("This is questionManagement");
    } else {
      this.$router.push({ query: {} });
    }
  },
  // 不推荐、用户体验不好
  watch: {
    $route(to, from) {
      this.$router.go(0);
    }
  }
};
</script>
